<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserCollect extends Model
{
    use SoftDeletes;
    protected $table = 'user_collects';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    public function article(){
        return $this -> hasOne(Article::class,'id','obj_id');
    }

    // 添加或取消 喜欢收藏
    public static function up($params){

        $data = [
            'user_id'   => auth() -> id(),
            'obj_id'    => $params['obj_id'],
            'obj_types' => $params['obj_types'],
            'types'     => $params['types']
        ];
        $collect = self::where($data) -> first();

        // 判断是否存在 存在就删除，不存在就新增
        if($collect){
            $res = $collect -> delete();
        }else{
            $res = self::create($data);
        }


        // 存储收藏数量
        if($params['obj_types'] == 1){

            unset($data['user_id']);
            $num = self::where($data) -> count();
            $article = Article::where('id',$data['obj_id']) -> first();
            $article -> {$data['types'] ==2 ? 'collect_num' : 'like_num'} = $num;
            $article -> save();
        }else if($params['obj_types'] == 2){ // 等于2 对商品的操作

            unset($data['user_id']);
            $num = self::where($data) -> count();
            $agric_goods = AgricGoods::where('id',$data['obj_id']) -> first();
            $agric_goods -> interested_num = $num;
            $agric_goods -> save();
        }else if($params['obj_types'] == 3){

            $field = $data['types'] ==2 ? 'collect_num' : 'like_num';
            if($collect){
                VillagePublish::where('id',$data['obj_id']) -> decrement($field);
            }else{
                VillagePublish::where('id',$data['obj_id']) -> increment($field);
            }
        }

        return $res;
    }

}
